﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SubSonic.Schema;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;

namespace WebeTerm.Model
{
    public interface IModel
    {
        IList<IColumn> GetDirtyColumns();

        void ClearDirtyColumns();

        bool IsNew();

        bool IsDirty();

        bool IsLoaded();

        void SetIsNew();

        void SetIsLoaded();
    }


    public abstract class BaseModel : IModel
    {
        private IList<IColumn> __dirtyColumns = new List<IColumn>();
        private bool isNew = true;
        private bool isLoaded = false;
        private ITable tbl;

        protected BaseModel(ITable tableInfo)
        {
            tbl = tableInfo;
        }


        //protected abstract ITable FindTable();

        protected void UpdateColumn(string columnName)
        {
            var col = tbl.Columns.FirstOrDefault(x => x.PropertyName.ToLower() == columnName.ToLower());
            if (IsLoaded() && __dirtyColumns.Any(l => l.Name == col.Name)) return;
            __dirtyColumns.Add(col);
        }

        #region IModel Members

        public IList<IColumn> GetDirtyColumns()
        {
            return __dirtyColumns;
        }

        public void ClearDirtyColumns()
        {
            __dirtyColumns.Clear();
        }

        public bool IsNew()
        {
            return isNew;
        }

        public bool IsDirty()
        {
            return __dirtyColumns.Count > 0;
        }

        public bool IsLoaded()
        {
            return isLoaded;
        }

        public void SetIsNew()
        {
            isNew = true;
            isLoaded = false;
            __dirtyColumns.Clear();
        }

        public void SetIsLoaded()
        {
            isNew = false;
            isLoaded = true;
            __dirtyColumns.Clear();
        }


        /// <summary>
        /// 把对象序列化并返回相应的字节
        /// </summary>
        /// <returns>byte[]</returns>
        public string SerializeObject()
        {
            StringBuilder sb = new StringBuilder(1024);
            StringWriter sw = new StringWriter(sb);
            XmlSerializer serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(sw, this);
            //return sb.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n", string.Empty).Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", string.Empty).Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", string.Empty).ToString();
            return sb.ToString();
        }
        #endregion
    }
}
